package com.yx.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yx.sys.entity.Role;
import com.yx.sys.entity.RoleMenu;
import com.yx.sys.entity.Tags;
import com.yx.sys.mapper.RoleMapper;
import com.yx.sys.mapper.RoleMenuMapper;
import com.yx.sys.mapper.TagsMapper;
import com.yx.sys.service.IRoleService;
import com.yx.sys.service.ITagsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 标签 服务实现类
 * </p>
 *
 * @author yx
 * @since 2023-02-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional
    public void addRole(Role role) {
//        写入角色表
        this.baseMapper.insert(role);
//        写入角色菜单关系表
        if(null != role.getMenuIdList()){
            for (Integer menuId:role.getMenuIdList()) {
                System.out.println(menuId);
                roleMenuMapper.insert(new RoleMenu(null, role.getRoleId(), menuId));
            }
        }
    }

    @Override
    public Role getRoleById(Integer roleId) {
        Role role = this.baseMapper.selectById(roleId);
        List<Integer> menuIdList = roleMenuMapper.getMenuIdListByRoleId(roleId);
        role.setMenuIdList(menuIdList);
        return role;
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
//        修改角色表
        this.baseMapper.updateById(role);
//        删除原有权限
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId,role.getRoleId());
        roleMenuMapper.delete(wrapper);
//        新增权限
        if(null != role.getMenuIdList()){
            for (Integer menuId:role.getMenuIdList()) {
                System.out.println(menuId);
                roleMenuMapper.insert(new RoleMenu(null, role.getRoleId(), menuId));
            }
        }

    }

    @Override
    @Transactional
    public void deleteUserById(Integer roleId) {
        this.baseMapper.deleteById(roleId);
        //        删除权限
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId,roleId);
        roleMenuMapper.delete(wrapper);
    }
}
